package com.corejsf;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.Date;
import java.util.Map;
import java.util.Set;

import javax.inject.Inject;
import javax.inject.Named;
import javax.annotation.PostConstruct;
import javax.enterprise.context.Conversation;
import javax.enterprise.context.ConversationScoped;
import javax.enterprise.context.SessionScoped;

@SuppressWarnings("serial")
@Named
@ConversationScoped
/**
 * The data sheet tables will draw all data from this class.
 * This class access' the activeUser and the list of worksheets from
 * the user.
 * @author Jitin Dhillon, Kelton Kowalchuk
 *
 */
public class TableData implements Serializable {
    @Inject Login login;
    /**
     * The employee number of the activeUser.
     */
    int eNum = login.getActiveUser().geteNumber();
    /**
     * The name of the activeUser.
     */
    String name = login.getActiveUser().getFullname();
    /**
     * Map containing all the worksheets of the activeUser;
     */
    Map<Integer , ArrayList<WorkSheet>> sheetMap;
    /**
     * List of all the weeks that have a sheet.
     */
    private ArrayList<Integer> weeks;
    /**
     * Select value for the drop down week list.
     */
    private int weekValue;
   
    private int selectedWeek;
    /**
     * Contains the rows of data for the Worksheet.
     */
	private static ArrayList<WorkSheet> names;
	/**
	 * True if the selected worksheet week matched the current week of the year.
	 */
	private boolean isCurrentWeek;
	
    Calendar date = Calendar.getInstance();
    /**
     * Current week of the month.
     */
    final int week; 

    /**
     * Current month of the year.
     */
    int month = date.get(Calendar.MONTH);
    /**
     * The week end day for the current week.
     */
    String weekEnd;
    /* Total Values for table footers */
    private double tsun;
    private double tmon;
    private double ttue;
    private double twed;
    private double tthu;
    private double tfri;
    private double tsat;
    private double ttotal;
    /* ^Total Values for table footers^ */
    @PostConstruct
    /**
     * Function that will automatically run and figure out the end of the week.
     */
    public void createCalendar() {
        SimpleDateFormat bartDateFormat = new SimpleDateFormat("MMMM d, yyyy");
        GregorianCalendar cal = new GregorianCalendar(); 
        cal.setTime(new Date());
        cal.set(GregorianCalendar.WEEK_OF_YEAR, week);
        cal.set(GregorianCalendar.DAY_OF_WEEK, GregorianCalendar.FRIDAY);
        weekEnd = bartDateFormat.format(cal.getTime());
    }
    
    /**
     * Constructor that draws the user data from the credentials bean.
     * Constructor will draw all keys from the map of WorkSheets to be used
     * in the change week drop down menu.
     */
    TableData(){
    	//Set the current week.
    	week = date.get(Calendar.WEEK_OF_YEAR);

    	selectedWeek = week;

    	weeks = new ArrayList<Integer>();

    	//Get the map of worksheets from the active user.
        sheetMap = login.getActiveUser().getSheetMap();
        
        //Create week if week does not exist
        if(!sheetMap.containsKey(week)) {
            ArrayList<WorkSheet> sheet = new ArrayList<WorkSheet>(Arrays.asList(
                    new WorkSheet(0, "", 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, "", true),
                    new WorkSheet(0, "", 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, "", true),
                    new WorkSheet(0, "", 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, "", true),
                    new WorkSheet(0, "", 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, "", true),
                    new WorkSheet(0, "", 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, "", true)
                ));
            sheetMap.put(week, sheet);
        }
        
        //copy the worksheet into bean variable.
    	names = sheetMap.get(week);
    	isCurrentWeek = true;
    	
    	//Extract map keys to be used in drop down menu to change weeks.
    	Set<Integer> keys = sheetMap.keySet();
    	for(int i : keys){
    		weeks.add(i);
    	}
    	
    	calcColumns(names);
    	
    }
    /**
     * Calculates column totals for hours.
     * @param sheet the sheet to calculate totals for.
     */
    public void calcColumns(ArrayList<WorkSheet> sheet){
    	double tsun1 = 0;
    	double tmon1 = 0;
    	double ttue1 = 0;
    	double twed1 = 0;
    	double tthu1 = 0;
    	double tfri1 = 0;
    	double tsat1 = 0;
    	for(WorkSheet s: sheet){
    		tsun1 += s.getSun();
            tmon1 += s.getMon();
            ttue1 += s.getTue();
            twed1 += s.getWed();
            tthu1 += s.getThu();
            tfri1 += s.getFri();
            tsat1 += s.getSat();
    	}
    	
    	tsun = tsun1;
        tmon = tmon1;
        ttue = ttue1;
        twed = twed1;
        tthu = tthu1;
        tfri = tfri1;
        tsat = tsat1;
        ttotal = tsun + tmon + ttue + twed + tthu + tfri + tsat;
    }
    /**
     * returns the array of worksheets.
     * @return the arrayList of worksheet rows.
     */
    public ArrayList<WorkSheet> getNames() { 
        return names;
    }
    
    /**
     * Saves all information in the worksheet.
     * @return
     */
    public String save() {
        for (WorkSheet name : names){
            name.setEditable(false);
            name.calcTotal();
        }
        calcColumns(names);
        return null;
    }

    /**
     * Log outs the current user.
     * And sets the activeUser to null.
     * @return navigation to the
     */
    public String logout(){
		login.setActiveUser(null);
		login.setPassword("");
		login.setPassword("");
		login.getConversation().end();
		return "login?faces-redirect=true";
	}
    
   /**
    * Delete the row from the worksheet.
    * @param sheet
    */
   public void delete(WorkSheet sheet){
	   names.remove(sheet);
   }
   
   /**
    * Add a empty row to the worksheet.
    */
   public void add(){
	   names.add(new WorkSheet(0, "", 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, "", true));
   }
   
   public int geteNum() {
       return eNum;
   }

   public void seteNum(int eNum) {
       this.eNum = eNum;
   }

   public String getName() {
       return name;
   }

   public void setName(String name) {
       this.name = name;
   }
   
   public int getWeek() {
       return week;
   }
    
        /**
         * Changes to a previous week worksheet and checks if it is the current week 
         * and wether or not to not display the edit or delete columns. If changing back to
         * current week it will display the editable fields. .
         */
    public void changeWeek(){
        names = sheetMap.get(weekValue);
        if(weekValue == week){
            isCurrentWeek = true;
    	} else {
    	    isCurrentWeek = false;
    	    for (WorkSheet name : names){
    	        name.setEditable(false);
    	        name.calcTotal();
    	    }
    	}
        selectedWeek = weekValue;
        SimpleDateFormat bartDateFormat = new SimpleDateFormat("MMMM d, yyyy");
        GregorianCalendar cal = new GregorianCalendar(); 
        cal.setTime(new Date());
        cal.set(GregorianCalendar.WEEK_OF_YEAR, selectedWeek);
        cal.set(GregorianCalendar.DAY_OF_WEEK, GregorianCalendar.FRIDAY);
        weekEnd = bartDateFormat.format(cal.getTime());
        Collections.sort(weeks);
        calcColumns(names);

    }
    
       public String getWeekEnd() {
           return weekEnd;
       }
    
       public void setWeekEnd(String weekEnd) {
           this.weekEnd = weekEnd;
       }
       public ArrayList<Integer> getWeeks() {
        	return weeks;
        }
       
        public void setWeeks(ArrayList<Integer> weeks) {
        	this.weeks = weeks;
        }

        public int getSelectedWeek() {
            return selectedWeek;
        }

		public int getWeekValue() {
			return weekValue;
		}
		
		public void setWeekValue(int weekValue) {
			this.weekValue = weekValue;
		}
		
		public boolean getIsCurrentWeek() {
			return isCurrentWeek;
		}
		
		public void setIsCurrentWeek(boolean isCurrentWeek) {
			this.isCurrentWeek = isCurrentWeek;
		}
		
        public void setSelectedWeek(int selectedWeek) {
            this.selectedWeek = selectedWeek;
        }

		public double getTsun() {
			return tsun;
		}

		public void setTsun(int tsun) {
			this.tsun = tsun;
		}

		public double getTmon() {
			return tmon;
		}

		public void setTmon(int tmon) {
			this.tmon = tmon;
		}

		public double getTtue() {
			return ttue;
		}

		public void setTtue(int ttue) {
			this.ttue = ttue;
		}

		public double getTwed() {
			return twed;
		}

		public void setTwed(int twed) {
			this.twed = twed;
		}

		public double getTthu() {
			return tthu;
		}

		public void setTthu(int tthu) {
			this.tthu = tthu;
		}

		public double getTfri() {
			return tfri;
		}

		public void setTfri(int tfri) {
			this.tfri = tfri;
		}

		public double getTsat() {
			return tsat;
		}

		public void setTsat(int tsat) {
			this.tsat = tsat;
		}

		public double getTtotal() {
			return ttotal;
		}

		public void setTtotal(double ttotal) {
			this.ttotal = ttotal;
		}
}